package com.oc.claimobs.bb.dao;

import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

public class BinaryFileDao {

	private static int _counter = 0;

	private String root;

	public BinaryFileDao(String rootPath) {
		root = rootPath;
	}

	public String saveBytes(byte[] _raw, String name, String extension)
			throws Exception {

		String fname = root + name + _counter + "." + extension;
		FileConnection file = (FileConnection) Connector.open(fname);

		while (file.exists()) {
			file.close();
			++_counter;
			fname = root + name + _counter + "." + extension;
			file = (FileConnection) Connector.open(fname);
		}

		// We know the file doesn't exist yet, so create it.
		file.create();

		// Write the image to the file.
		OutputStream out = file.openOutputStream();
		out.write(_raw);

		// Close the connections.
		out.close();
		file.close();

		// Increment the image counter.
		++_counter;

		return fname;
	}

	public boolean delete(String name, String extension) {
		try {

			FileConnection file = (FileConnection) Connector.open(name + "."
					+ extension);

			if (file.exists()) {
				file.delete();
			}
			return true;

		} catch (Exception e) {
			return false;
		}

	}

}
